﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.Data;

public partial class CRM_Store_ERP_OutStoreEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int c = BindCenterStore(Store_Rome, Request.QueryString["ptabid"]);
            if (c > 0)
                extcomb_StoreRoomId.SelectedIndex = 0;
            string objid = ViewState_ObjID = string.IsNullOrEmpty(Request.QueryString["ObjId"]) ? "Add" : Request.QueryString["ObjId"];
            ShowEditInfo(objid);
        }
    }

    private void ShowEditInfo(string objid)
    {
        if (objid == "Add")
        {
            exttxtf_InUserName.Text = BS_LoginUserName;
            exthidn_InUser.Text = BS_LoginUserID;
            exttxtf_InDate.Text = DateTime.Now.ToDateTimeString();
        }
        else
        {
            var planDataTable = CRMMis.BLL.ERP_OutBound.GetList("BoundId=" + objid).Tables[0];
            if (planDataTable.Rows.Count > 0)
            {
                DataRow row = planDataTable.Rows[0];
                int planState = Convert.ToInt32(row["State"]);
                //根据状态控制
                if (planState != 1)
                    extBtn_CheckInfo.Hidden = true;
                if (planState > 0)
                {
                    extBtn_SubmitInfo.Hidden = true;
                    extBtn_Save.Hidden = true;
                    extBtn_AddItem.Hidden = extBtn_DeleteItem.Hidden = extBtn_AddBook.Hidden = true;
                    SetContainerReadOnly(formPanel, true);
                    gridPanel_listdata.ColumnModel.Columns[1].Editable =                //商品名称
                        gridPanel_listdata.ColumnModel.Columns[5].Editable = false;     //数量
                }
                if (planState > 1)
                {
                    extBtn_CheckInfo.Hidden = true;
                }
                SetContainer(formPanel, planDataTable);
                //单独绑定客户
                DataTable suppData = CRMMis.BLL.ERP_Customer.GetList("CustomerId=" + row["CustomerId"], "CustomerName,Spell,Address").Tables[0];
                Store_Customer.DataSource = suppData;
                Store_Customer.DataBind();

                var planDetail = CRMMis.BLL.ERP_OutBoundDetail.GetList(" DBoundId=" + objid).Tables[0];
                Store1.DataSource = planDetail;
                Store1.DataBind();
                extcomb_CustomerId.ReadOnly = extcomb_StoreRoomId.ReadOnly = planDetail.Rows.Count > 0;
            }
        }
    }

    [DirectMethod]
    public void BindCargoComb(string searchText)
    {
        string sqWhere = " state=1 and CusDetailState=1 and  Count>0 and CustomId="
            + Convert.ToInt32(extcomb_CustomerId.Value) + 
            " and StoreRoomId=" + Convert.ToInt32(extcomb_StoreRoomId.Value);
        if (!string.IsNullOrEmpty(searchText))
        {
            sqWhere += " and( CargoName like '%" + FilterSpecChar(searchText) + "%' or Spell like '%" + FilterSpecChar(searchText) + "%') ";
        }
        var datatable = CRMMis.BLL.ERP_StockDetail.GetListCustomer(sqWhere, " CargoName asc").Tables[0];
        store_Cargo.DataSource = datatable;
        store_Cargo.DataBind();
    }

    [DirectMethod]
    public void SelectedSalesPlan(int planId)
    {
        int i = 1;
        var planDetail = CRMMis.BLL.ERP_OutBoundDetail.GetList(" 1=2 ").Tables[0].Copy();
        string whereTmp = " CargoId={0} and state=1 and CusDetailState=1 and  Count>0 and CustomId="
            + Convert.ToInt32(extcomb_CustomerId.Value) +
            " and StoreRoomId=" + Convert.ToInt32(extcomb_StoreRoomId.Value);
        var pladDetail = CRMMis.BLL.ERP_SalesPlanDetail.GetList("DSalesPlanId=" + planId).Tables[0];
        foreach (DataRow planItem in pladDetail.Rows)
        {
            int planCount = Convert.ToInt32(planItem["DCount"]);
            string sqWhere = string.Format(whereTmp, planItem["DCargoId"]);
            var datatable = CRMMis.BLL.ERP_StockDetail.GetListCustomer(sqWhere, " CargoName asc").Tables[0];
            foreach (DataRow row in datatable.Rows)
            {
                if (planCount < 1)
                    break;
                int hasCount = Convert.ToInt32(row["count"]);
                int outCount = planCount;
                if (outCount > hasCount)
                {
                    outCount = hasCount;
                    planCount = planCount - outCount;
                }
                else
                {
                    planCount = 0;
                }
                decimal Supplyprice = Convert.ToDecimal(row["Supplyprice"]);
                DataRow nrow = planDetail.NewRow();
                nrow["DetailId"] = i++;
                //nrow["CargoId"] = row["CargoId"];
                nrow["CargoName"] = row["CargoName"];
                nrow["ItemId"] = row["ItemId"];
                nrow["BatchNo"] = row["BatchNo"];
                nrow["CargoCode"] = row["CargoCode"];
                nrow["Spec"] = row["Spec"];
                nrow["Area"] = row["Area"];
                nrow["Unit"] = row["Unit"];
                nrow["CusDetailId"] = row["CusDetailId"];
                nrow["Supplyprice"] = Supplyprice;
                nrow["Count"] = outCount;
                nrow["TotalPrice"] = Supplyprice * outCount;
                planDetail.Rows.Add(nrow);
            }
        }
        Store1.DataSource = planDetail;
        Store1.DataBind();
        exthidn_SalesId.Text = planId.ToString();
        extcomb_CustomerId.ReadOnly = extcomb_StoreRoomId.ReadOnly = planDetail.Rows.Count > 0;

    }

    /// <summary>
    /// 保存，
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="type">0,保存;1,提交;2,审核</param>
    [DirectMethod]
    public void SaveData(string jsonData,int type)
    {
        List<CRMMis.Model.ERP_OutBoundDetail> details = JSON.Deserialize<List<CRMMis.Model.ERP_OutBoundDetail>>(jsonData);
        CRMMis.Model.ERP_OutBound outModel;
        if (ViewState_ObjID == "Add")
        {
            outModel = new CRMMis.Model.ERP_OutBound();
            outModel.BoundId = CRMMis.BLL.ERP_OutBound.GetNewID();
            outModel.BoundNo = GetBusinessNo("CK", "ERP_OutBoundCK", Convert.ToInt32(extcomb_StoreRoomId.Value).ToString("000"));
            outModel.DeliveryNo = GetBusinessNo("SH", "ERP_OutBoundDeliverySH", Convert.ToInt32(extcomb_CustomerId.Value).ToString("000"));
            outModel.InUser = BS_LoginUserID;
            outModel.InDate = exttxtf_InDate.Text.Trim();
            outModel.State = 0;
            if (type == 1)
                outModel.State = 1;    //提交
        }
        else
        {
            outModel = CRMMis.BLL.ERP_OutBound.GetModel(Convert.ToInt32(ViewState_ObjID));
            if (type == 1)
            {
                if (outModel.State == 0)
                    outModel.State = 1;    //提交
                else
                {
                    X.Msg.Alert("系统提示", "提交失败！当前记录已经提交").Show();
                    return;
                }
            }
            else if (type == 2)
            {
                if (outModel.State == 1)
                    outModel.State = 2;    //审核
                else
                {
                    X.Msg.Alert("系统提示", "审核失败！当前记录已经审核").Show();
                    return;
                }
            }

        }
        if (type < 2)
        {
            outModel.StoreRoomId = Convert.ToInt32(extcomb_StoreRoomId.Value);
            outModel.Remark = exttxtf_Remark.Text.Trim();
            outModel.CustomerId = Convert.ToInt32(extcomb_CustomerId.Value);
            outModel.SalesId = string.IsNullOrEmpty(exthidn_SalesId.Text) ? 0 : Convert.ToInt32(exthidn_SalesId.Text);
        }
        CommonLib.BLL.MyTransaction myTrans = new CommonLib.BLL.MyTransaction();
        myTrans.BeginTransaction();
        try
        {
            if (ViewState_ObjID == "Add")
            {
                CRMMis.BLL.ERP_OutBound.Add(myTrans, outModel);
            }
            else
            {
                CRMMis.BLL.ERP_OutBound.Update(myTrans, outModel);
                //删除子表
                if (type < 2)
                    CRMMis.BLL.ERP_OutBoundDetail.DeleteFK(myTrans, "DBoundId = " + outModel.BoundId);
                //处理审核
                if (type == 2)
                    CheckInfo(myTrans, outModel);
            }
            if (type < 2)
            {
                int orderNo = 0;
                foreach (CRMMis.Model.ERP_OutBoundDetail detailModel in details)
                {
                    orderNo++;
                    detailModel.DetailId = CRMMis.BLL.ERP_OutBoundDetail.GetNewID();
                    detailModel.DBoundId = outModel.BoundId;
                    detailModel.OrderId = orderNo;
                    string msg = CRMMis.BLL.ERP_StockDetail.GetLockCargo(myTrans, detailModel.ItemId, detailModel.Count);
                    if (msg != null)
                        throw new Exception("序号为" + orderNo + "的物品," + msg);
                    CRMMis.BLL.ERP_OutBoundDetail.Add(myTrans, detailModel);
                }
            }
            myTrans.CommitTran();
            ViewState_ObjID = outModel.BoundId.ToString();
            exttxtf_BoundNo.Text = outModel.BoundNo;

            string handler = "";
            if (type > 0)
                handler = "closeCurrTab();";
            X.Msg.Alert("系统提示", "保存成功！", handler).Show();
        }
        catch(Exception ex)
        {
            myTrans.RollBackTran();
            X.Msg.Alert("系统提示", "保存失败！</br>" + ex.Message).Show();
        }
    }

    #region 客户选择

    protected void StoreCustomer_Refresh(object sender, StoreRefreshDataEventArgs e)
    {
        var qStr = GetCustomerQryString();
        int recordcount = CRMMis.BLL.ERP_Customer.GetRecorderCount(qStr);
        int PageSize = extcomb_CustomerId.PageSize;
        int CurPage = e.Start / PageSize + 1;
        e.Total = recordcount;
        DataTable suppData = CRMMis.BLL.ERP_Customer.GetPageList(PageSize, CurPage, qStr, "CustomerName,Spell,Address").Tables[0];
        Store_Customer.DataSource = suppData;
        Store_Customer.DataBind();
    }

    private string GetCustomerQryString()
    {
        string StrSql = "DelState=0 ";
        string selText = FilterSpecChar(extcomb_CustomerId.SelectedItem.Text.Trim());
        if (!string.IsNullOrEmpty(selText))
            StrSql += " and ( CustomerName like '%" + selText + "%' or Spell like '%" + selText + "%') ";
        return StrSql;
    }

    #endregion


    /// <summary>
    /// 处理审核
    /// </summary>
    /// <param name="myTrans"></param>
    /// <param name="outModel"></param>
    public void CheckInfo(CommonLib.BLL.MyTransaction myTrans, CRMMis.Model.ERP_OutBound outModel)
    {
        outModel.CheckUser = BS_LoginUserID;
        outModel.CheckDate = DateTime.Now.ToString();
        outModel.State = 2;
        CRMMis.BLL.ERP_OutBound.Update(myTrans, outModel);

        var ReturnList = CRMMis.BLL.ERP_OutBoundDetail.GetList(myTrans, " DBoundId=" + outModel.BoundId, "OrderId").Tables[0];
        foreach (DataRow row in ReturnList.Rows)
        {
            CRMMis.Model.ERP_BusinessLog BusModel = new CRMMis.Model.ERP_BusinessLog();
            BusModel.LogId = CRMMis.BLL.ERP_BusinessLog.GetNewID();
            BusModel.ActionId = 2;
            BusModel.ActionName = "出库";
            BusModel.ActionUser = outModel.InUser;
            BusModel.StoreRoom_Id = outModel.StoreRoomId.ToString();
            BusModel.ActionDate = outModel.CheckDate;
            //ERP_StockDetail 表
            var stockDetail = CRMMis.BLL.ERP_StockDetail.GetModel(myTrans,Convert.ToInt32(row["ItemId"]));
            if (stockDetail != null)
            {
                stockDetail.Count -= Convert.ToInt32(row["Count"]);
                CRMMis.BLL.ERP_StockDetail.Update(myTrans, stockDetail);
            }
            //ERP_StockInfo 表
            var model = CRMMis.BLL.ERP_StockInfo.GetModel(myTrans, stockDetail.StoreId);
            BusModel.DetailId = model.DetailId;
            DataTable dt = CRMMis.BLL.ERP_Cargo_Detail.GetList("DetailId=" + model.DetailId).Tables[0];
            BusModel.CargoName = dt.Rows[0]["CargoName"].ToString();
            BusModel.Spec = dt.Rows[0]["Spec"].ToString();
            BusModel.Area = dt.Rows[0]["Area"].ToString();
            BusModel.Version = dt.Rows[0]["Version"].ToString();
            BusModel.ProduceName = dt.Rows[0]["ProduceName"].ToString();
            BusModel.BatchNo = row["BatchNo"].ToString();
            BusModel.SupplyPrice = decimal.Parse(dt.Rows[0]["SupplyPrice"].ToString());
            BusModel.CustomId = outModel.CustomerId;
            if (model != null)
            {
                BusModel.CurCount = model.Count;
                BusModel.Count = Convert.ToInt32(row["Count"]);
                model.Count -= Convert.ToInt32(row["Count"]);
                CRMMis.BLL.ERP_StockInfo.Update(myTrans, model);
            }
            BusModel.State = 0;
            BusModel.BusniessNo = outModel.DeliveryNo;
            CRMMis.BLL.ERP_BusinessLog.Add(myTrans, BusModel);
        }
    }

    #region 加载销售计划

    protected void extBtn_SalesPlan_Click(object sender, DirectEventArgs e)
    {
        if (extcomb_CustomerId.Text == "")
        {
            X.Msg.Alert("系统提示", "请先选择客户！").Show();
            return;
        }
        if (extcomb_StoreRoomId.Text == "")
        {
            X.Msg.Alert("系统提示", "请先选择库房！").Show();
            return;
        }
        string Url = G_Url_allstring + "/CRM_Manager/ERP_SalesPlanSelect.aspx?ptabid=" + Request.QueryString["tabid"] + ",Store1";
        ResourceManager1.AddScript("popTopwinWithId('SalesPlanSelect','" + Url + "&ObjId=Add&customerId=" + extcomb_CustomerId.SelectedItem.Value + "&storeroomId=" + extcomb_StoreRoomId.SelectedItem.Value + "', '选择销售计划', 800, 600,AfterOperate);");
    }

    #endregion

}